package com.stone.serverless.sdk;

import net.sf.cglib.proxy.Enhancer;

import java.lang.reflect.Proxy;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/18 13:42
 * @Version: 1.0.0
 */
public class ProxyClassConfig {

    public static Object proxy(Class type, ClassLoader classLoader, Object handler) {
        Object obj = null;
        //接口的话就基于jdk
        if (type.isInterface()) {
            obj = Proxy.newProxyInstance(classLoader, new Class[]{type}, convert(handler));
        } else {
            Enhancer enhancer = new Enhancer();
            //设置需要创建子类的类
            enhancer.setSuperclass(type);
            enhancer.setClassLoader(classLoader);
            enhancer.setCallback(convert(handler));
            //通过字节码技术动态创建子类实例
            obj = enhancer.create();
        }
        return obj;
    }

    public static <T> T convert(Object t) {
        return (T) t;
    }
}
